import asyncio
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.layers import get_channel_layer


class YourConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        """
        当客户端请求连接时调用
        """
        # 接受连接，也就是握手的环节
        # print(self.channel_name)
        await self.accept()
        print("连接成功")

    async def receive(self, text_data=None, bytes_data=None):
        """
        当客户端发送消息时调用
        """
        print('接收到：')
        print(text_data)
        count = 123
        while True:
            await self.send(text_data=json.dumps({'count': count}))
            # try:
            #     await self.channel_layer.send( self.channel_name,{'count': count})
            # except Exception as e:
            #     print(f"发送消息失败: {e}")
            count += 1
            await asyncio.sleep(0.5)

    async def disconnect(self, close_code):
        """
        当客户端断开连接时调用
        """
        print(f"连接断开，关闭代码: {close_code}")


# consumers.py

class StudentCountConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.school_id = self.scope['url_route']['kwargs']['id']
        self.group_name = f'student_count_{self.school_id}'

        # 加入组当作一个数组加入就行了所有在线人员都在一个组里面
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()
        print(f"已连接到组: {self.group_name}")  # 确认已连接

    async def disconnect(self, close_code):
        # 离开组
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    async def update_student_post_count(self, event):
        count = event['post_count']
        await self.send(text_data=json.dumps({
            'post_count': count
        }))

    async def update_student_count(self, event):
        try:
            count = event['count']
            await self.send(text_data=json.dumps({
                'count': count
            }))
        except Exception as e:
            print(f"发送消息失败: {e}")

    async def update_order_count(self, event):
        count = event['or_count']
        await self.send(text_data=json.dumps({
            'or_count': count
        }))
        print(f"发送新的订单计数: {count}")  # 确认收到消息


class communicate(AsyncWebsocketConsumer):
    # 用于存储在线用户及其通道名称
    active_users = {}

    async def connect(self):
        self.user_name = self.scope['url_route']['kwargs']['username']  # 从 URL 中获取用户名前缀
        self.active_users[self.user_name] = self.channel_name  # 将用户与其通道名称关联

        await self.accept()
        print(f"连接成功: {self.user_name}")

    async def disconnect(self, close_code):
        # 从字典中移除
        if self.user_name in self.active_users:
            del self.active_users[self.user_name]
        print(f"连接断开: {self.user_name}，关闭代码: {close_code}")

    async def receive(self, text_data=None, bytes_data=None):
        data = json.loads(text_data)
        message = data.get('message')
        recipient = data.get('recipient')

        if recipient in self.active_users:
            # 向特定的用户发送消息
            recipient_channel_name = self.active_users[recipient]
            await self.channel_layer.send(recipient_channel_name, {

                'type': 'chat.message',
                'message': message,
                'sender': self.user_name
            })
        else:
            print(f"用户 {recipient} 不在线")

    async def chat_message(self, event):
        message = event['message']
        sender = event['sender']
        await self.send(text_data=json.dumps({
            'message': message,
            'sender': sender
        }))


# 存储连接的用户及其通道名的字典
connected_users = {}

from channels.generic.websocket import AsyncWebsocketConsumer
import json
from Student.models import *
from asgiref.sync import sync_to_async

connected_user = {}


class ChatConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        self.student_nickname = self.scope['url_route']['kwargs']['nickname']
        connected_user[self.student_nickname] = self.channel_name
        await self.accept()
        print(f"{self.student_nickname} 连接成功")

    async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        recipient_id = text_data_json['recipient']
        is_read = False

        print(f'接收到来自 {self.student_nickname} 的消息: {message}，发送给: {recipient_id}')

        # 保存聊天记录
        # if recipient_id in connected_user:
        #     is_read = True
        await self.save_chat_message(self.student_nickname, recipient_id, message, is_read)

        # 查找目标用户的通道名并发送消息
        if recipient_id in connected_user:
            recipient_channel_name = connected_user[recipient_id]
            await self.channel_layer.send(
                recipient_channel_name,
                {
                    'type': 'chat_message',
                    'message': message,
                    'sender': self.student_nickname
                }
            )
        else:
            # 如果接收者不在线，可以选择记录离线消息
            print(f'用户 {recipient_id} 啊不在线，将存储消息.')

    async def disconnect(self, close_code):
        if self.student_nickname in connected_user:
            del connected_user[self.student_nickname]  # 移除用户通道名
        print(f"{self.student_nickname} 连接断开，关闭代码: {close_code}")

    async def chat_message(self, event):
        message = event['message']
        sender = event['sender']

        await self.send(text_data=json.dumps({
            'sender': sender,
            'message': message
        }))

    @sync_to_async
    def save_chat_message(self, sender_id, recipient_id, message, is_read):
        print('发送者', sender_id)
        print('接收者', recipient_id)
        sender = Student.objects.get(nickname=sender_id)
        print(sender)
        receiver = Student.objects.get(nickname=recipient_id)
        print(receiver)
        print('保存消息')
        # 将消息保存到数据库
        try:
            ChatMessage.objects.create(sender=sender, receiver=receiver, message=message, is_read=is_read)
        except Exception as e:
            print(e)
